package cn.xz.mytimer

import android.animation.Animator
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import cn.xz.mytimer.databinding.ActivityMainBinding
import java.util.*

class MainActivity : AppCompatActivity() {

    private lateinit var mDataBind: ActivityMainBinding
    private var calendar: Calendar? = null
    private var mHour = 0
    private var tts: TextToSpeech? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //设置屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        mDataBind = DataBindingUtil.setContentView(this, R.layout.activity_main)
        //开始动点
        showM()
        //获取时间
        getTime()
        initEvent()
    }

    override fun onResume() {
        super.onResume()
        //动态显示空间
        initView()
    }

    private fun getTime(){
        //获取时间管理器
        calendar = Calendar.getInstance()
        //开启定时器
        toNow()
    }

    private fun initEvent(){
        mDataBind.tvSetting.setOnClickListener {
            val intent = Intent(this, SettingActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            this.startActivity(intent)
        }
        mDataBind.tvWeek.setOnClickListener {
            finish()
        }
    }


    //定时器
    private var timer: Timer? = null

    private fun toNow(){
        timer = Timer()
        val timerTask: TimerTask = object : TimerTask() {
            override fun run() {
                calendar = null
                calendar = Calendar.getInstance()
                mDataBind.ivHourLeft.post {
                    //年
                    val year: Int = calendar!!.get(Calendar.YEAR)
                    //月
                    val month: Int = calendar!!.get(Calendar.MONTH) + 1
                    //日
                    val day: Int = calendar!!.get(Calendar.DAY_OF_MONTH)
                    setYear(year,month,day)
                    //小时
                    val hour: Int = calendar!!.get(Calendar.HOUR_OF_DAY)
                    setView(mDataBind.ivHourLeft, mDataBind.ivHourRight, hour)
                    mHour = hour
                    setAllBG(hour)
                    setMinBg(hour,false)
                    //分钟
                    val minute: Int = calendar!!.get(Calendar.MINUTE)
                    setView(mDataBind.ivMinLeft, mDataBind.ivMinRight, minute)
                    //秒
                    val second: Int = calendar!!.get(Calendar.SECOND)
                    setView(mDataBind.ivSLeft, mDataBind.ivSRight, second)
                    setAni(second)
                    //周几
                    val week: Int = calendar!!.get(Calendar.DAY_OF_WEEK)
                    setWeek(week)
                    //闹钟
                    setNZ(hour, minute)
                }
            }
        }
        timer?.schedule(timerTask, 0, 1000) //开启定时
    }

    //根据时间动态设置大背景
    private fun setAllBG(hour: Int){
        if (hour > 18 || hour < 6){
            //夜间模式
            if (!mDataBind.lotBgNight.isVisible){
                mDataBind.lotBgNight.visibility = View.VISIBLE
                mDataBind.lotBgNight.playAnimation()
                mDataBind.lotBgDay.visibility = View.INVISIBLE
                mDataBind.lotBgDay.pauseAnimation()
            }
        }else{
            //日间模式
            if (mDataBind.lotBgNight.isVisible){
                mDataBind.lotBgNight.visibility = View.INVISIBLE
                mDataBind.lotBgNight.pauseAnimation()
                mDataBind.lotBgDay.visibility = View.VISIBLE
                mDataBind.lotBgDay.playAnimation()
            }
        }
    }

    //根据时间动态设置秒数背景
    private fun setMinBg(hour: Int,s: Boolean){
        //下午六点到早上六点-夜间模式
        if (hour > 18 || hour < 6){
           //夜间模式
            if (!mDataBind.lotWeekNight.isVisible || s){
                mDataBind.lotWeekNight.visibility = View.VISIBLE
                mDataBind.lotWeekNight.playAnimation()
                mDataBind.lotWeekDay.visibility = View.INVISIBLE
                mDataBind.lotWeekDay.pauseAnimation()
            }
        }else{
            //日间模式
            if (mDataBind.lotWeekNight.isVisible || s){
                mDataBind.lotWeekNight.visibility = View.INVISIBLE
                mDataBind.lotWeekNight.pauseAnimation()
                mDataBind.lotWeekDay.visibility = View.VISIBLE
                mDataBind.lotWeekDay.playAnimation()
            }
        }
    }

    //缩放动画
    private fun showM(){
        val animation = ScaleAnimation(1f,0.7f,1f,0.7f,
            Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f)
        animation.duration = 500
        animation.fillAfter = true
        animation.repeatMode = Animation.REVERSE
        animation.repeatCount = Animation.INFINITE
        mDataBind.ivM.startAnimation(animation)
    }

    //根据时间添加图片
    private fun setView(iLeft: ImageView,iRight: ImageView,i: Int){
        val split = i.toString().split("")
        var mDra: Drawable? = null
        var id: Int = -1
        split.forEachIndexed { index, s ->
            if (s.isNotEmpty()) {
                when (s.toInt()) {
                    0 -> {
                        id = R.mipmap.icon_0
                    }
                    1 -> {
                        id = R.mipmap.icon_1
                    }
                    2 -> {
                        id = R.mipmap.icon_2
                    }
                    3 -> {
                        id = R.mipmap.icon_3
                    }
                    4 -> {
                        id = R.mipmap.icon_4
                    }
                    5 -> {
                        id = R.mipmap.icon_5
                    }
                    6 -> {
                        id = R.mipmap.icon_6
                    }
                    7 -> {
                        id = R.mipmap.icon_7
                    }
                    8 -> {
                        id = R.mipmap.icon_8
                    }
                    9 -> {
                        id = R.mipmap.icon_9
                    }
                }
                if (id != -1) {
                    mDra = ContextCompat.getDrawable(this, id)
                    if (mDra != null) {
                        if (i < 10){
                            iLeft.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_0))
                            iRight.setImageDrawable(mDra)
                        }else{
                            if (index == 1) {
                                iLeft.setImageDrawable(mDra)
                            } else if (index == 2) {
                                iRight.setImageDrawable(mDra)
                            }
                        }
                    }
                }
            }
        }
    }

    //年月日
    private fun setYear(n: Int,y: Int,r: Int){
        val mS = "${n}-${y}-${r}"
        if (mDataBind.tvYear.text != mS){
            mDataBind.tvYear.text = mS
        }
    }

    //周几
    private fun setWeek(week: Int){
        var mStr = ""
        when(week - 1){
            0->{
                mStr = "星期天"
            }
            1->{
                mStr = "星期一"
            }
            2->{
                mStr = "星期二"
            }
            3->{
                mStr = "星期三"
            }
            4->{
                mStr = "星期四"
            }
            5->{
                mStr = "星期五"
            }
            6->{
                mStr = "星期六"
            }
        }
        if (mDataBind.tvWeek.text != mStr){
            mDataBind.tvWeek.text = mStr
        }
    }

    private fun setNZ(hour: Int,min: Int){
        //是否开启了闹钟
        if (SessionUtils.getBoolean(SessionUtils.SHOW_NZ,false)){
            var nowTimer =  ""
            nowTimer = if (hour < 10){
                "0${hour}"
            }else{
                "$hour"
            }
            nowTimer += if (min < 10){
                "0${min}"
            }else{
                "$min"
            }
            val nOldTimer = SessionUtils.getString(SessionUtils.MY_TIMER,"0000")
            if (nOldTimer == nowTimer){
                //到达闹钟时间
                speak(SessionUtils.getString(SessionUtils.MY_NZ_CONTENT,"闹钟时间到了"))
                //是否重复，如果不重复，自动关闭闹钟
                if (!SessionUtils.getBoolean(SessionUtils.NZ_CF,false)){
                    SessionUtils.commitBoolean(SessionUtils.SHOW_NZ,false)
                }
            }
        }
    }

    //每20秒随机产生一个动画,同时产生一句话
    //上次播放的分钟
    private var lastMin = 0
    private fun setAni(min: Int){
        if (SessionUtils.getBoolean(SessionUtils.SHOW_ANI,true)){
            val mTime = SessionUtils.getInt(SessionUtils.SHOW_ANI_TIME,20)
            if (min - lastMin > mTime || min - lastMin < -mTime){
                //动画
                val x = Random().nextInt(16) //0-15
                val mL = "lottie/ai${x}.json"
                mDataBind.lotAi.visibility = View.VISIBLE
                mDataBind.lotAi.clearAnimation()
                mDataBind.lotAi.setAnimation(mL)
                mDataBind.lotAi.playAnimation()
                mDataBind.lotAi.addAnimatorListener(object : Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        mDataBind.lotAi.visibility = View.GONE
                        getAI()
                    }

                    override fun onAnimationCancel(animation: Animator) {
                    }

                    override fun onAnimationRepeat(animation: Animator) {
                    }

                })
                lastMin = min
            }
        }
    }

    private fun initView(){
        //年
        if (SessionUtils.getBoolean(SessionUtils.SHOW_YEAR,true)){
            mDataBind.tvYear.visibility = View.VISIBLE
            mDataBind.lotYear.visibility = View.VISIBLE
        }else{
            mDataBind.tvYear.visibility = View.INVISIBLE
            mDataBind.lotYear.visibility = View.INVISIBLE
        }
        //星期
        if (SessionUtils.getBoolean(SessionUtils.SHOW_WEEK,true)){
            mDataBind.tvWeek.visibility = View.VISIBLE
            mDataBind.lotWeek.visibility = View.VISIBLE
        }else{
            mDataBind.tvWeek.visibility = View.INVISIBLE
            mDataBind.lotWeek.visibility = View.INVISIBLE
        }
        //秒
        if (SessionUtils.getBoolean(SessionUtils.SHOW_S,true)){
            mDataBind.llcMin.visibility = View.VISIBLE
            setMinBg(mHour,true)
        }else{
            mDataBind.llcMin.visibility = View.INVISIBLE
            //动画
            mDataBind.lotWeekNight.visibility = View.INVISIBLE
            mDataBind.lotWeekNight.pauseAnimation()
            mDataBind.lotWeekDay.visibility = View.INVISIBLE
            mDataBind.lotWeekDay.pauseAnimation()
        }
    }

    //语音
    private fun speak(mS: String){
        if (tts == null){
            tts = TextToSpeech(this) { p0 ->
                if (p0 == TextToSpeech.SUCCESS) {
                    val result = tts?.setLanguage(Locale.CHINA)
                    if (result == TextToSpeech.LANG_MISSING_DATA ||
                        result == TextToSpeech.LANG_NOT_SUPPORTED
                    ) {
                        Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            tts!!.setPitch(1.0f) //设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
            tts!!.setSpeechRate(0.5f) //设置语速
        }
        tts!!.speak(mS, TextToSpeech.QUEUE_ADD, null);
    }

    //智能语音
    private fun getAI(){
        if (SessionUtils.getBoolean(SessionUtils.ZN_AI,false)){
            //五分之一的概率，说一句土味情话
            val x = Random().nextInt(5)
            if (x == 0){
                OkHttpUtil.toGet("https://api.uomg.com/api/rand.qinghua",object :
                    OkHttpUtil.RequestSuccess<AIBean> {
                    override fun success(data: AIBean?) {
                        if (data?.content != null &&data.content!!.isNotEmpty()){
                            speak(data.content!!)
                        }
                    }

                    override fun error() {
                    }

                },AIBean::class.java)
            }
        }
    }

    override fun onBackPressed() {}

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null){
            timer!!.cancel()
            timer = null
        }
        if (tts != null){
            tts?.stop() //停止播放
            tts?.shutdown() //释放资源
            tts = null
        }
    }
}